import * as React from "react";
import { Component } from "react";
import { Table, Input, Select, Button, Modal, message, Space } from "antd";
import IconFont from "../../../../assets/ICON";
import { PlusOutlined } from "@ant-design/icons";
import moment from "moment";
import {
  terminalmanagementList,
  agreementList,
  terminaladd,
  terminaldelete,
} from "../deviceseversapi";
import "./index.less";
import { AjaxData } from "../../../../data/interface/publicInterface";
import { ergodicListAddIdToKey } from "../../../../utils/common";

export interface ScreenProps {}
const { Option } = Select;
export interface ScreenState {
  type: Number;
  time: "date" | "time" | "month" | "year" | "week" | "quarter";
  loading: boolean;
  selectedRowKeys: number[];
  visible: boolean;
  binding: boolean;
  datalist: number[];
  status: number;
  id: string;
  conditionname: string;
  conditionno: string;
  conditionaddress: string;
  addtitle: string;
  batch: string;
  condition: string;
  // id:number[];
  adddate: {
    name: string;
    address: string;
    no: string;
    typeId: string;
    pwd: string;
    installAdd: string;
    typeName: string;
  };
  adddate1: {
    name: string;
    address: string;
    no: string;
    typeId: string;
    pwd: string;
    installAdd: string;
    typeName: string;
  };
  addedit: number;
  protocollist: number[];
  page: number;
  size: number;
  total: number;
  // isModalVisible:Boolean;
  // setIsModalVisible:Boolean;
}
export enum dateEnum {
  "date" = "date",
  "time" = "time",
  "month" = "month",
  "year" = "year",
}

interface provinceClass {
  name: string;
  id: number;
}

class TerminalManagement extends Component<ScreenProps, ScreenState> {
  state = {
    type: 1,
    time: dateEnum.date,
    selectedRowKeys: [], // Check here to configure the default column
    loading: false,
    isModalVisible: false,
    visible: false,
    binding: false,
    addtitle: "新增",
    batch: "删除终端设备信息",
    terminallist: {},
    id: "",
    datalist: [],
    status: 1, //1就是删除 2是解绑 3是绑定
    conditionno: "",
    conditionname: "",
    conditionaddress: "",
    condition: "", //新增协议默认内容  编辑协议文本
    adddate: {
      name: "",
      address: "",
      no: "",
      typeId: "",
      pwd: "",
      installAdd: "",
      typeName: "",
    },
    adddate1: {
      name: "",
      address: "",
      no: "",
      typeId: "",
      pwd: "",
      installAdd: "",
      typeName: "",
    },
    protocollist: [],
    page: 1,
    size: 10,
    total: 0,

    // id:0,
    addedit: 1, //1新增或者2编辑
  };
  private columns = [
    {
      key: "no",
      title: "终端编号",
      dataIndex: "no",
      width: 100,
    },
    {
      key: "name",
      title: "终端名称",
      dataIndex: "name",
      width: 200,
    },
    {
      key: "typeName",
      title: "协议名称",
      dataIndex: "typeName",
      width: 100,
    },
    {
      key: "address",
      title: "通讯地址",
      dataIndex: "address",
      width: 100,
    },
    {
      key: "installAdd",
      title: "安装位置",
      dataIndex: "installAdd",
      width: 100,
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      width: 100,
      render: (text, record, index) => {
        let newDate = moment(record.changeTime, "x").format("YYYY-MM-DD HH:mm"); //parse string
        return <span>{newDate}</span>;
      },
    },
    {
      title: "操作",
      key: "address",
      width: 150,
      render: (text, record) => (
        <Space size="middle">
          <Button
            type="text"
            icon={
              <IconFont style={{ color: "#FBB10B" }} type="icon_form_bianji" />
            }
            onClick={() => {
              this.setState({
                visible: true,
                addedit: 2,
                addtitle: "编辑",
                adddate: record,
                // condition:record.
              });
            }}
          >
            编辑
          </Button>
          <Button
            type="text"
            onClick={(event: any) => {
              this.setState({
                binding: true,
                batch: "删除终端设备信息",
                //  deletedate:event.id,
                id: record.id,
                status: 1,
              });
            }}
            icon={
              <IconFont style={{ color: "#FF6B6B" }} type="icon_form_shanchu" />
            }
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];
  componentDidMount() {
    this.fetchget();
    this.agreement();
  }

  onSelectChange = (selectedRowKeys) => {
    this.setState({ selectedRowKeys });
  };
  //新增change事件
  /* adddate:{
      'name':"",
      'address':"",
      'no':"",
      'typeId':1,
      'pwd':'',
      'installAdd':''
    } */

  render() {
    //添加弹窗操作
    const showModal = () => {
      // this.fetchget();
      this.setState({
        visible: true,
        addedit: 1,
        addtitle: "新增",
        adddate: this.state.adddate1,
      });
    };

    const handleOk = () => {
      // let that = this;
      if (this.state.adddate.name === "") {
        message.info("终端名称不能为空");
        return;
      }
      if (this.state.adddate.address === "") {
        message.info("终端地址不能为空");
        return;
      }
      if (this.state.adddate.typeId === "") {
        message.info("终端协议不能为空");
        return;
      }
      if (this.state.adddate.no === "") {
        message.info("终端编号不能为空");
        return;
      }
      let _this = this;
      terminaladd(this.state.adddate).then((res: any) => {
        if (res) {
          if (res.code === 200) {
            this.fetchget();
            message.info("成功");
            _this.setState({
              visible: false,
            });
          } else {
            message.error(res.message);
          }
        }
      });
    };
    //获取协议类型下拉

    const handleCancel = () => {
      this.setState({
        visible: false,
      });
    };
    //绑定事件
    // const bindingModal = () => {
    //   this.setState({
    //     binding: true,
    //   });
    // };
    // //解绑
    // const unbundleModal = () => {
    //   this.setState({
    //     binding: true,
    //   });
    // };
    // //删除
    // const deleteModal = () => {
    //   this.setState({
    //     binding: true,
    //   });
    // };
    //绑定 解绑 删除后根据条件调用接口
    const bindingOk = () => {
      if (this.state.status === 1) {
        let data = {
          id: this.state.id,
        };
        terminaldelete(data).then((res: any) => {
          if (res) {
            if (res.code === 200) {
              this.fetchget();
              message.info("删除成功");
              this.setState({
                binding: false,
              });
            } else {
              message.error(res.message);
            }
          }
        });
      }

      this.setState({
        binding: false,
      });
    };

    const bindingCancel = () => {
      this.setState({
        binding: false,
      });
    };

    // const { loading, selectedRowKeys } = this.state;
    const selectedRowKeys = this.state.selectedRowKeys;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    //表格复选框
    let that = this;
    let pagination = {
      total: this.state.total,
      defaultCurrent: this.state.page,
      pageSize: this.state.size,
      showSizeChanger: true,
      onShowSizeChange: (current, pageSize) => {},
      onChange: (current, pageSize) => {
        that.setState(
          {
            page: current,
          },
          () => {
            this.fetchget();
          }
        );
      },
    };
    return (
      <>
        <div className="TerminalManagement">
          <div className="rowcon_body">
            <div className="querystat">
              终端编号：
              <Input
                className="input"
                placeholder="请输入终端编号"
                value={this.state.conditionno}
                onChange={(event) => {
                  this.numberchange(event);
                }}
              />
            </div>
            <div className="query">
              终端名称：
              <Input
                className="input"
                placeholder="请输入终端名称"
                value={this.state.conditionname}
                onChange={(event) => {
                  this.namechange(event);
                }}
              />
            </div>
            <div className="query">
              终端地址：
              <Input
                className="input"
                placeholder="请输入终端地址"
                value={this.state.conditionaddress}
                onChange={(event) => {
                  this.conditionaddress(event);
                }}
              />
            </div>
            <div className="query">
              <Button
                type="primary"
                onClick={() => {
                  this.fetchget();
                }}
              >
                查询
              </Button>
            </div>
          </div>
          <div className="subject">
            <div className="operation">
              <Button
                type="primary"
                className="increased"
                size="middle"
                icon={<PlusOutlined />}
                onClick={showModal}
              >
                新增
              </Button>
            </div>
            <div>
              <Table
                style={{ paddingTop: 16 }}
                rowSelection={rowSelection}
                columns={this.columns}
                dataSource={this.state.datalist}
                pagination={pagination}
              />
            </div>
          </div>
          <div>
            {/* 新增或者编辑弹窗 */}
            <Modal
              title={this.state.addtitle}
              visible={this.state.visible}
              onOk={handleOk}
              onCancel={handleCancel}
              width="682px"
            >
              <div className="addtotality">
                <div className="addsingle">
                  <div className="addparty">
                    <div className="addtext">
                      <span className="required">*</span>
                      终端名称：
                    </div>
                    <Input
                      className="addinput"
                      placeholder="请输入终端名称"
                      value={this.state.adddate.name}
                      onChange={(event) => {
                        this.addnamechange(event);
                      }}
                    />
                  </div>
                  <div className="addparty">
                    <div className="addtext">
                      <span className="required">*</span>终端地址：
                    </div>
                    <Input
                      className="addinput"
                      placeholder="请输入终端地址"
                      value={this.state.adddate.address}
                      onChange={(event) => {
                        this.addresschange(event);
                      }}
                    />
                  </div>
                </div>
                <div className="addsingle">
                  <div className="addparty">
                    <div className="addtext">
                      <span className="required">*</span>终端编号：
                    </div>
                    <Input
                      className="addinput"
                      placeholder="请输入终端地址"
                      value={this.state.adddate.no}
                      onChange={(event) => {
                        this.nochange(event);
                      }}
                    />
                  </div>
                  <div className="addparty">
                    <div className="addtext">
                      <span className="required">*</span>协议类型：
                    </div>
                    <Select
                      defaultValue={this.state.adddate.typeId}
                      className="addinput"
                      onChange={(event) => {
                        this.onSecondCityChange(event);
                      }}
                    >
                      {this.state.protocollist.map(
                        (province: provinceClass) => (
                          <Option key={province.id} value={province.id}>
                            {province.name}
                          </Option>
                        )
                      )}
                    </Select>
                  </div>
                </div>
                <div className="addsingle">
                  <div className="addparty">
                    <div className="addtext">
                      <span className="required"></span>终端密码：
                    </div>
                    <Input
                      className="addinput"
                      placeholder="请输入终端密码"
                      value={this.state.adddate.pwd}
                      onChange={(event) => {
                        this.pwdchange(event);
                      }}
                    />
                  </div>
                  <div className="addparty">
                    <div className="addtext">
                      <span className="required"></span>安装位置：
                    </div>
                    <Input
                      className="addinput"
                      placeholder="请输入安装位置"
                      value={this.state.adddate.installAdd}
                      onChange={(event) => {
                        this.installAddchange(event);
                      }}
                    />
                  </div>
                </div>
              </div>
            </Modal>
            {/* 绑定弹窗 */}
            <Modal
              title="请确认"
              visible={this.state.binding}
              onOk={() => {
                bindingOk();
              }}
              onCancel={bindingCancel}
            >
              <div>
                <div></div>
                <div>确认要{this.state.batch}</div>
              </div>
            </Modal>
          </div>
        </div>
      </>
    );
  }
  async fetchget() {
    let data = {
      pageIndex: this.state.page,
      pageSize: this.state.size,
      queryData: {
        address: this.state.conditionaddress,
        name: this.state.conditionname,
        no: this.state.conditionno,
      },
    };
    let res: any = await terminalmanagementList(data).catch((err) => {
      console.log(err);
    });
    const json: AjaxData = res;

    if (json.success) {
      this.setState({
        datalist: ergodicListAddIdToKey(json.data.records),
        total: json.data.total,
      });
    }
  }
  namechange(e) {
    this.setState({
      conditionname: e.target.value,
    });
  }
  numberchange(e) {
    this.setState({
      conditionno: e.target.value,
    });
  }
  conditionaddress(e) {
    this.setState({
      conditionaddress: e.target.value,
    });
  }
  //新增change事件
  //终端名称
  addnamechange(e) {
    // let inputName = e.target.name;
    let inputValue = e.target.value;

    let jasperCopy = Object.assign({}, this.state.adddate);

    jasperCopy.name = inputValue;
    this.setState({
      adddate: jasperCopy,
    });
  }
  //终端地址
  addresschange(e) {
    // let inputName = e.target.name;
    let inputValue = e.target.value;

    let jasperCopy = Object.assign({}, this.state.adddate);

    jasperCopy.address = inputValue;
    this.setState({
      adddate: jasperCopy,
    });
  }
  //终端编号
  nochange(e) {
    // let inputName = e.target.name;
    let inputValue = e.target.value;

    let jasperCopy = Object.assign({}, this.state.adddate);

    jasperCopy.no = inputValue;
    this.setState({
      adddate: jasperCopy,
    });
  }
  //终端密码
  pwdchange(e) {
    // let inputName = e.target.name;
    let inputValue = e.target.value;

    let jasperCopy = Object.assign({}, this.state.adddate);

    jasperCopy.pwd = inputValue;
    this.setState({
      adddate: jasperCopy,
    });
  }
  //安装位置
  installAddchange(e) {
    // let inputName = e.target.name;
    let inputValue = e.target.value;
    let jasperCopy = Object.assign({}, this.state.adddate);
    jasperCopy.installAdd = inputValue;
    this.setState({
      adddate: jasperCopy,
    });
  }
  //新增协议选择
  onSecondCityChange = (value) => {
    let inputValue = value;
    let jasperCopy = Object.assign({}, this.state.adddate);
    jasperCopy.typeId = inputValue;
    // for (let i in this.state.protocollist)
    // {
    //   // if(this.state.protocollist[i]==value){

    //   // }
    // }
    this.setState({
      adddate: jasperCopy,
    });
  };
  //获取协议类型下拉
  async agreement() {
    let res: any = await agreementList().catch((err) => {
      console.log(err);
    });
    const json: any = res;
    if (res) {
      this.setState({
        protocollist: json.data,
      });
    }
  }
}

export default TerminalManagement;
